 /**
 *
 * ......................我佛慈悲.......................
 *                       _oo0oo_
 *                      o8888888o
 *                      88" . "88
 *                      (| -_- |)
 *                      0\  =  /0
 *                    ___/`---'\___
 *                  .' \\|     |// '.
 *                 / \\|||  :  |||// \
 *                / _||||| -卍-|||||- \
 *               |   | \\\  -  /// |   |
 *               | \_|  ''\---/''  |_/ |
 *               \  .-\__  '-'  ___/-. /
 *             ___'. .'  /--.--\  `. .'___
 *          ."" '<  `.___\_<|>_/___.' >' "".
 *         | | :  `- \`.;`\ _ /`;.`/ - ` : | |
 *         \  \ `_.   \_ __\ /__ _/   .-` /  /
 *     =====`-.____`.___ \_____/___.-`___.-'=====
 *                       `=---='
 *
 *..................佛祖开光 ,永无BUG....................
 *         CSDN博客:http://blog.csdn.net/song5347
 *       github地址:https://github.com/lingsuiderongyan
 *             邮箱:lingsuiderongyan@163.com
 */

import UIKit
import SVProgressHUD
import AFNetworking

//微博App Key
let WeiboAppKey = "1511347690"

//微博AppSecret
let WeiboAppSecret = "2527bf173129b801dae0091b718c5934"

//微博授权回调页
let WeiboRedirect_Uri = "http://wow.duowan.com"

class LSOAuthViewController: UIViewController {

    //MARK: - 懒加载
    private lazy var webView: UIWebView = UIWebView()
    
    override func loadView() {
        //改成透明的
        webView.opaque = false
        
        //设置代理
        webView.delegate = self
        
        view = webView
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        setNavUI()
        requestOAuthLogin()
    }
    
    //MARK: - 设置按钮\标题
    private func setNavUI() {
        
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "取消", target: self, action: "cancelAction")
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "自动填充", target: self, action: "autoFillAction")
        navigationItem.title = "微博登录"
    }
    
    //MARK: - 点击事件
    @objc private func cancelAction() {
        
        SVProgressHUD.dismiss()
        
        dismissViewControllerAnimated(true, completion: nil)
        
    }
    
    //MARK: - 自动填充
    @objc private func autoFillAction() {
        
        webView.stringByEvaluatingJavaScriptFromString("document.getElementById('userId').value = '18301172373';document.getElementById('passwd').value = 'songzhanbo1989'")
        
    }
    
    //MARK: - 请求第三方登录页
    private func requestOAuthLogin() {
        
        //准备url
        let url = "https://api.weibo.com/oauth2/authorize?client_id=\(WeiboAppKey)&redirect_uri=\(WeiboRedirect_Uri)"
        
        print(url)
        
        //准备urlRequest
        let urlRequest = NSURLRequest(URL: NSURL(string: url)!)
        
        //通过webView加载页面
        webView.loadRequest(urlRequest)
    }
    
//    //MARK: - 通过code获取accesstoken
//    private func reqeustAccessTokenWithCode(code: String) {
//        
//        LSNetworkTools.sharedTools.reqeustAccessTokenWithCode(code) { (response, error) -> () in
//            
//            if error != nil {
//                print("网络请求失败\(error)")
//                return
//            }
//            
//            //  代码执行到此网络请求成功
//            
//            //  判断服务端给的数据是否是一个正确的字典
//            guard let dic = response as? [String: AnyObject] else {
//                print("不是一个正确的字典格式")
//                return
//            }
//            //  代码执行到此,字典没有问题
//            let userAccount = LSUserAccount(dic: dic)
//            print(userAccount.access_token)
//            //  请求用户基本信息
//            self.requestUserInfo(userAccount)
//            
//        }
    
//        //准备url
//        let url = "https://api.weibo.com/oauth2/access_token"
//        
//        //准备参数
//        let params = [
//            "client_id": WeiboAppKey,
//            "client_secret": WeiboAppSecret,
//            "grant_type": "authorization_code",
//            "code": code,
//            "redirect_uri": WeiboRedirect_Uri
//        ]
//        
//        //创建sessionManager
//        let sessionManager = AFHTTPSessionManager()
//        //创建相应可接受的类型
//        sessionManager.responseSerializer.acceptableContentTypes?.insert("text/plain")
//        
//        sessionManager.POST(url, parameters: params, progress: nil, success: { (_, response) -> Void in
//            
//            //判断服务端给的数据是否是一个正确的字典
//            guard let dic = response as? [String: AnyObject] else {
//                print("不是正确的字典格式")
//                return
//            }
//            
//            //代码执行到这,字典没有问题
//            let userAccount = LSUserAccount(dic: dic)
//            print(userAccount.access_token)
//            
//            //请求用户基本信息
//            self.requestUserInfo(userAccount)
//            
//            
//            }) { (_, error) -> Void in
//                print(error)
//        }
//    }
    
//    //通过access和uid获取用户信息
//    private func requestUserInfo(userAccount: LSUserAccount) {
//        
//        LSNetworkTools.sharedTools.requestUserInfo(userAccount) { (response, error) -> () in
//            
//            if error != nil {
//                print("网络请求错误, \(error)")
//                return
//            }
//            
//            //代码执行到这,表示网络请求成功
//            guard let dic = response as? [String: AnyObject] else {
//                print("不是正确的")
//                return
//            }
//            
//            //代码执行到这,表示字典没问题
//            let name = dic["name"]
//            let avatar_large = dic["avatar_large"]
//            
//            userAccount.name = name as? String
//            userAccount.avatar_large = avatar_large as? String
//            
//            print(userAccount)
//            
//            //表示用户登录成功,保存用户账号的类型
//            userAccount.saveUserAccount()
//            
//        }
    
//        //准备url
//        let url = "https://api.weibo.com/2/users/show.json"
//        //准备参数
//        let params = [
//            "access_token": userAccount.access_token!,
//            "uid": "\(userAccount.uid)"
//        ]
//        
//        let path = url + "?access_token=" + userAccount.access_token! + "&uid=" + "\(userAccount.uid)"
//        print("--" + path)
//        
//        //创建sessionManager对象
//        let sessionManager = AFHTTPSessionManager()
//        sessionManager.responseSerializer.acceptableContentTypes?.insert("text/plain")
//        
//        //发送get请求
//        sessionManager.GET(url, parameters: params, progress: nil, success: { (_, response) -> Void in
//            
//            //判断服务端给的是否是一个正确的json数据
//            guard let dic = response as? [String: AnyObject] else {
//                print("不是正确的字典数据")
//                return
//            }
//            //代码执行到这,字典没有问题
//            let name = dic["name"]
//            let avatar_large = dic["avatar_large"]
//            
//            userAccount.name = name as? String
//            userAccount.avatar_large = avatar_large as? String
//            print(userAccount)
//            
//            //表示用户登录成功
//            //保存用户账号的模型
//            userAccount.saveUserAccount()
//            
//            }) { (_, error) -> Void in
//                print(error)
//        }
//    }
}

//MARK: - UIWebViewDelegate代理
extension LSOAuthViewController:UIWebViewDelegate {
    
    //将要加载过来
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        
        print(request.URL?.absoluteString)
        
        guard let url = request.URL else {
            return false
        }
        
        if !url.absoluteString.hasPrefix(WeiboRedirect_Uri) {
        return true
        }
        //代码执行到这,url一定有值
        //代码执行到此,是我们的回调页打头
        if let query = url.query where query.hasPrefix("code=") {
            
            print(query)
            //获取code
            let code = query.substringFromIndex("code=".endIndex)
            print(code)

            //获取accesstoken
            //reqeustAccessTokenWithCode(code)
            LSUserAccountViewModel.sharedUserAccount.reqeustAccessTokenWithCode(code, callBack: { (isSuccess) -> () in
                
                if isSuccess {
                    print("登录成功")
                    
                    //切换根视图控制器需要在线dismis完成以后闭包里面,否则present这个控制器不会释放
                    self.dismissViewControllerAnimated(false, completion: { () -> Void in
                        NSNotificationCenter.defaultCenter().postNotificationName(SwitchRootVCNotification, object: self)
                    })

                    
                } else {
                    print("登录失败")
                }
                
            })
        } else {
            dismissViewControllerAnimated(true, completion: nil)
        }
        //只想取到code,不像看页面,用false,看页面改成true即可
        return false
    }
    
    //MARK: - 转动
    //开始加载
    func webViewDidStartLoad(webView: UIWebView) {
        SVProgressHUD.show()
    }
    
    //加载完成
    func webViewDidFinishLoad(webView: UIWebView) {
        SVProgressHUD.dismiss()
    }
    
    //加载失败
    func webView(webView: UIWebView, didFailLoadWithError error: NSError?) {
        SVProgressHUD.dismiss()
    }
}















